package com.gisuni.sddc.platformManager.service;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import com.gisuni.sddc.platformManager.dao.OrganizationDao;
import com.gisuni.sddc.platformManager.model.Organization;
import com.gisuni.sddc.platformManager.model.OrganizationWytzTarget;
import com.gisuni.sddc.platformManager.model.Response;
import com.gisuni.sddc.platformManager.model.Tree;
import com.gisuni.sddc.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

@IocBean
public class OrganizationService  {
	
	
	private Log log = Logs.getLog(OrganizationService.class);    
    @Inject
    private OrganizationDao  organizationDao;
    
    public List<Tree> findTree(String condition) {
        List<Tree> trees = new ArrayList<Tree>();

        String sql = "select t.id,t.parent_id,t.organization_name,t.organization_type from SDDCGISPLATFORM.organization t where 1=1 ";
		
        if(!StringUtil.isNullOrEmpty(condition)){ 
			if("parentOrg".equals(condition)){  //新增组织机构时,上级部门只有集团/事业两级
				sql+=" and organization_type !='3' ";
			}
        	
		} 
        List<Organization> organizationFather = organizationDao.findOrganizationAll(sql);

      if (organizationFather != null) {
	      for (Organization organizationOne : organizationFather) {
	          Tree treeOne = new Tree();
	
	          treeOne.setId(organizationOne.getId());
	          treeOne.setText(organizationOne.getOrganizationName());
	          treeOne.setPid(organizationOne.getParentId());
	          if("2".equals(organizationOne.getOrganizationType())&& !"parentOrg".equals(condition) ){ //新增用户时只展开两级
	        	  treeOne.setState("closed");
	          }
	          trees.add(treeOne);
	      }
      }
 
        return trees;
    }

    
    public String findTreeGrid() {
//    	未关联指标时的sql
    	String sql = " select t.id,t.parent_id,t.organization_name,t.organization_type,t1.displayname MENAGER_NAME from SDDCGISPLATFORM.organization t"+
    				" left join SDDCGISPLATFORM.User_Info t1 on t.organization_manager_id=t1.user_id";
    	
    	/**
    	 *   select t.id,t.parent_id,t.organization_name,t.organization_type,t1.displayname MENAGER_NAME,
  			vCompany.wytz_type companyWytzType,vCompany.target companyTarget,vBusiness.wytz_type businessWytzType,vBusiness.target businessTarget,vDevelop.wytz_type developWytzType,vDevelop.target developTarget from SDDCGISPLATFORM.organization t 
         left join SDDCGISPLATFORM.User_Info t1 on t.organization_manager_id=t1.user_id 
         left join v_org_company_target vCompany on t.id = vCompany.org_id
         left join v_org_business_target vBusiness on t.id = vBusiness.org_id
         left join v_org_develop_target vDevelop on t.id = vDevelop.org_id
    	 */
    	
    	//关联了指标的
    	StringBuffer sqlSbf = new StringBuffer();
    	sqlSbf.append("select t.id,t.parent_id,t.organization_name,t.organization_type,t1.displayname MENAGER_NAME,");
		sqlSbf.append(" vCompany.wytz_type companyWytzType,vCompany.target companyTarget,vBusiness.wytz_type businessWytzType,vBusiness.target businessTarget,vDevelop.wytz_type developWytzType,vDevelop.target developTarget from SDDCGISPLATFORM.organization t ");
		sqlSbf.append(" left join SDDCGISPLATFORM.User_Info t1 on t.organization_manager_id=t1.user_id ");
		sqlSbf.append(" left join v_org_company_target vCompany on t.id = vCompany.org_id");
		sqlSbf.append(" left join v_org_business_target vBusiness on t.id = vBusiness.org_id");
		sqlSbf.append(" left join v_org_develop_target vDevelop on t.id = vDevelop.org_id");
    	
    	 List<Organization> list =  organizationDao.queryOrganizationAll(sqlSbf.toString());
//    	 List<Organization> list =  organizationDao.findOrganizationAll(sql);
    	 JSONArray jsonArray = new JSONArray();
        if(list!=null && list.size()>0){
            for(Organization org : list){
                JSONObject jo = new JSONObject();
                jo.put("id", org.getId());
                jo.put("organizationName", org.getOrganizationName());
                jo.put("type", org.getOrganizationType());
                jo.put("parentId",org.getParentId());
                jo.put("managerName", org.getManagerName());
                jo.put("hechaTarget", org.getHechaTarget());
                jo.put("qiatanTarget", org.getQiatanTarget());
//                jo.put("state", "closed");
                jsonArray.put(jo);
            }
        }
        String result =  jsonArray.toString();
        return result;
    }

    public Organization findOrganizationById(String id) {
    	
        return organizationDao.findOrganizationById(id);
    }
    
    public Response addOrganization( HttpServletRequest request) throws Exception{
    	 Response res = new Response();
    	 res.setSuccess(false);
    	 try{
        	 String organizationName = request.getParameter("name");
    		 String managerUserId = request.getParameter("managerUser");
    		 String parentId = request.getParameter("pid");
    		 String type = request.getParameter("type");
    		 String hechaTarget  = request.getParameter("hechaTarget");
    		 String qiatanTarget = request.getParameter("qiatanTarget");
    		 
    		 //TODO 指标的校验 前端已做数字检验
    		 
    		 //TODO 类型需与上级部门有限制
    				
    		 Organization org = new Organization();
    		 org.setOrganizationName(organizationName);
    		 org.setOrganizationMenagerId(managerUserId);
    		 if(StringUtil.isNullOrEmpty(parentId)){
    			 parentId="0";
    		 }
    		 org.setParentId(parentId);
    		 org.setOrganizationType(type);
    		 String orgId = UUID.randomUUID().toString().replaceAll("-", "");
    		 org.setId(orgId);
    		 
    		 //非拓展组不能设置指标
    		 if(!"3".equals(type)){
    			 hechaTarget = null;
    			 qiatanTarget = null;
    		 }
    		 
    		 //保存 组织 
    		 boolean flag  = organizationDao.addOrganization(org);
    		 
    		 if(flag){
    			  flag = setOrgTarget("1",orgId, hechaTarget, qiatanTarget, null);
    			  if(flag){
    				  res.setSuccess(true);
    			  }else{
    				  res.setMsg("保存组织指标失败");
    				  log.error("保存组织指标失败:"+orgId+new Date());
    			  }
    		 } 
    	 }catch(Exception e){
       		 e.printStackTrace();
       		 log.error(e);
       		 res.setMsg("操作失败");
       		 return res;
       	 }
		 
		return res;
    }


	public Response updateOrganization(HttpServletRequest request) {
	   	 Response res = new Response();
	   	 res.setSuccess(false);
   	 try{
   	 	 String organizationName = request.getParameter("name");
		 String managerUserId = request.getParameter("managerUser");
		 String parentId = request.getParameter("pid");
		 String type = request.getParameter("type");
		 String id = request.getParameter("id");
		 
		 String hechaTarget  = request.getParameter("hechaTarget");
		 String qiatanTarget = request.getParameter("qiatanTarget");
		 String oldhechaTarget = request.getParameter("oldhechaTarget");
		 String oldqiatanTarget = request.getParameter("oldqiatanTarget");
		 
		 if((hechaTarget+"").equals(oldhechaTarget+"")){
			 hechaTarget=null;
		 }
		 if((qiatanTarget+"").equals(oldqiatanTarget+"")){
			 qiatanTarget=null;
		 }
		 //TODO 指标的校验
		 
		 //TODO 类型需与上级部门有限制 校验
		 
		 Organization org = new Organization();
		 org.setOrganizationName(organizationName);
		 org.setOrganizationMenagerId(managerUserId);
		 org.setParentId(parentId);
		 org.setOrganizationType(type);
		 org.setId(id);
		 
		 boolean flag  = organizationDao.updateOrganization(org);
		 if(flag){
			  flag = setOrgTarget("2",id, hechaTarget, qiatanTarget, null);
			  if(flag){
				  res.setSuccess(true);
			  }else{
				  res.setMsg("保存组织指标失败");
				  log.error("保存组织指标失败:"+id+new Date());
			  }
		 } 
	 }catch(Exception e){
   		 e.printStackTrace();
   		 log.error(e);
   		 res.setMsg("操作失败");
   		 return res;
   	 }
		 
		return res;
	}
	
	
	//设置组织-指标
	public boolean setOrgTarget(String auMark ,String orgId , String hechaTarget,String qiatanTarget,String huoquTarget){
		//TODO 这个方法得放在一个事务中 sql放一起执行
		 boolean flag = true ; 
		 String sql =null ;
		 String id = UUID.randomUUID().toString().replaceAll("-", "");
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 String now = sdf.format(new Date());
		 
		 //插入新核查指标
		 if(!StringUtil.isNullOrEmpty(hechaTarget)){
			  sql = " update sddcgisplatform.ORGANIZATION_WYTZ_TARGET set status='0',end_time=to_date('"+now+"', 'yyyy-MM-dd HH24:mi:ss') where ORGANIZATION_ID='"+orgId+"' and id != '"+id+"' and wytz_type='1'"; //更新之前的指标状态
			  flag = organizationDao.executeSql(sql);
			  sql = " insert into sddcgisplatform.ORGANIZATION_WYTZ_TARGET(id,ORGANIZATION_ID,WYTZ_TYPE,STATUS,TARGET) values('"+id+"1','"+orgId+"','1','1','"+hechaTarget+"')";//更新之前的指标状态
			  flag = organizationDao.executeSql(sql);			  
		 }
		//插入新洽谈指标
		 if(!StringUtil.isNullOrEmpty(qiatanTarget)&&flag){
			  sql = " update sddcgisplatform.ORGANIZATION_WYTZ_TARGET set status='0',end_time=to_date('"+now+"', 'yyyy-MM-dd HH24:mi:ss') where ORGANIZATION_ID='"+orgId+"' and id != '"+id+"'  and wytz_type='2'"; //更新之前的指标状态
			  flag = organizationDao.executeSql(sql);
			  sql = " insert into sddcgisplatform.ORGANIZATION_WYTZ_TARGET(id,ORGANIZATION_ID,WYTZ_TYPE,STATUS,TARGET) values('"+id+"2','"+orgId+"','2','1','"+qiatanTarget+"')";
			  organizationDao.executeSql(sql);

		 }
		 
		 // 失败需指标删除数据
		 if(!flag){
			 organizationDao.executeSql("delete from sddcgisplatform.ORGANIZATION_WYTZ_TARGET where id='"+id+"1'");
			 organizationDao.executeSql("delete from sddcgisplatform.ORGANIZATION_WYTZ_TARGET where id='"+id+"2'");
			 return flag;
		 }
		  
		return flag;
	}
	
    public Response deleteOrganizationById(String id) {
   	 Response res = new Response();
      	 res.setSuccess(false);
      	 try{
			Organization org = new Organization();
			org.setId(id);
			
			int flag  = organizationDao.delOrganization(org);
			 if(flag==1){
				 res.setSuccess(true);
			 }else if(flag==0){
				 res.setSuccess(false);
				 res.setMsg("操作失败");
			 }else if(flag==2){
				 res.setSuccess(false);
				 res.setMsg("存在下级组织,不能删除");
			 }
			 return res;
      	 }catch(Exception e){
      		 e.printStackTrace();
      		 log.error(e);
      		 res.setMsg("操作失败");
      		 return res;
      	 }

   }

}
